<template>
  <a-drawer
    style="height: 100%"
    :width="520"
    :closable="true"
    :mask="false"
    :wrap-style="{ position: 'absolute' }"
    placement="left"
    :visible="visible"
    wrapClassName="sk-left-drawer track_drawer"
    getContainer=".skpz"
    @close="close"
  >
    <div
      v-if="isAddStatus"
      class="ctr"
      style="position: sticky; top: 0; margin-top: -24px; z-index: 2;background: #fff; border-bottom: 1px solid rgb(232, 232, 232);"
    >
      <a-space>
        <a-button type="primary" class="btn" @click="onAdd('add')">输入轨迹点</a-button>
        <a-tooltip placement="topRight">
          <template slot="title">
            <span>支持直接点击地图进行位置打点</span>
          </template>
          <a-icon type="exclamation-circle" :style="{ color: '#ccc', fontSize: '24px' }"/>
        </a-tooltip>
        <a-button type="primary" class="btn" @click="onDetail()">查看任务轨迹点</a-button>
      </a-space>
    </div>
    <div class="skpz-table">
      <a-table
        class="sk-add-table"
        :columns="listObject.columns"
        :loading="listLoading"
        :dataSource="listObject.list"
        :pagination="false"
      >
        <span slot="order" slot-scope="text, record, index">{{ index + 1 }}</span>
        <template v-for="col in ['longitude', 'latitude', 'range']" :slot="col" slot-scope="text, record">
          <div :key="col">
            <template v-if="col === 'range'">
              <span v-if="record.editable" style="display: flex;">
                <a-time-picker
                  style="width:90px;margin-right:5px;"
                  v-model="record.beginTime"
                  format="HH:mm:ss"
                  valueFormat="HH:mm:ss"
                  placeholder="请选择"
                />
                <a-time-picker
                  style="width:90px;"
                  v-model="record.endTime"
                  format="HH:mm:ss"
                  valueFormat="HH:mm:ss"
                  placeholder="请选择"
                />
              </span>
              <!-- <a-range-picker
                v-if="record.editable"
                :defaultValue="
                  record.beginTime
                    ? [
                        moment(record.beginTime, 'YYYY-MM-DD HH:mm:ss'),
                        moment(record.endTime, 'YYYY-MM-DD HH:mm:ss')
                      ]
                    : null
                "
                :showTime="{
                  hideDisabledOptions: true,
                  defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('11:59:59', 'HH:mm:ss')]
                }"
                format="YYYY-MM-DD HH:mm:ss"
                style="width: 240px;"
                @change="(date, dateString) => changeRange(date, dateString, record.key)"
              /> -->
              <span v-else-if="record.beginTime && record.endTime">{{ record.beginTime }} ~ {{ record.endTime }}</span>
            </template>
            <a-input
              v-else-if="record.editable && record.type === 'add'"
              style="margin: -5px 0"
              :value="text"
              placeholder="请输入"
              @change="e => handleChange(e.target.value, record.key, col)"
            />
            <template v-else>{{ text }}</template>
          </div>
        </template>
        <template slot="action" slot-scope="text, record" v-if="isAddStatus">
          <div class="editable-row-operations">
            <span v-if="record.editable">
              <a href="javascript:;" @click="onSave(record.key)">保存</a>
              <a href="javascript:;" class="font-gray" style="margin-left: 12px;" @click="onCancel(record.key)">取消</a>
            </span>
            <span v-else>
              <a href="javascript:;" @click="onEdit(record.key)">编辑</a>
              <!-- <a href="javascript:;" @click="onCopy(record.key)" >复制</a> -->
              <a-popconfirm title="确定删除该轨迹吗?" @confirm="onDelete(record.key)">
                <a href="javascript:;" style="margin: 0 12px;" class="font-red">删除</a>
              </a-popconfirm>
            </span>
          </div>
        </template>
      </a-table>
    </div>
    <!-- position: 'absolute', bottom: 0, -->
    <div
      :style="{
        left: 0,
        width: '100%',
        borderTop: '1px solid #E8E8E8',
        padding: '15px 16px 5px',
        textAlign: 'right',
        bottom: '0',
        position: 'absolute',
        backgroundColor: '#fff',
        zIndex: 1
      }"
    >
      <!-- <a-button :style="{ marginRight: '8px' }" @click="cancel">取消</a-button> -->
      <a-button
        v-if="isAddStatus"
        type="primary"
        :loading="loading"
        @click="onSubmit"
        class="sure"
        :style="{ 'background-color': 'rgba(24,76,151,1);', 'border-color': 'rgba(24,76,151,1);' }"
        >保存</a-button
      >
    </div>
  </a-drawer>
</template>

<script>
import moment from 'moment'
import { trim, testFloat } from '@/libs/tools'
export default {
  props: ['isAdd', 'addPoint', 'visible'],
  data() {
    return {
      listObject: {
        list: [],
        columns: []
      },
      columns1: [
        {
          title: '序号',
          dataIndex: 'order',
          width: 50,
          align: 'center',
          scopedSlots: { customRender: 'order' }
        },
        {
          title: '经度',
          dataIndex: 'longitude',
          width: 90,
          scopedSlots: { customRender: 'longitude' }
        },
        {
          title: '纬度',
          dataIndex: 'latitude',
          width: 80,
          scopedSlots: { customRender: 'latitude' }
        },
        {
          title: '时间',
          dataIndex: 'range',
          width: 120,
          scopedSlots: { customRender: 'range' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 100,
          scopedSlots: { customRender: 'action' }
        }
      ],
      columns2: [
        {
          title: '序号',
          dataIndex: 'order',
          width: 50,
          scopedSlots: { customRender: 'order' }
        },
        {
          title: '经度',
          dataIndex: 'longitude',
          width: 80,
          scopedSlots: { customRender: 'longitude' }
        },
        {
          title: '纬度',
          dataIndex: 'latitude',
          width: 80,
          scopedSlots: { customRender: 'latitude' }
        },
        {
          title: '时间',
          dataIndex: 'range',
          width: 180,
          scopedSlots: { customRender: 'range' }
        }
      ],
      editForm: {},
      cacheData: [],
      count: 0,
      errorTaskName: false,
      errorTxt: '',
      loading: false,
      listLoading: false,
      isAddStatus: true,
      taskId: ''
    }
  },
  mounted() {
    this.cacheData = this.listObject.list.map(item => ({ ...item }))
  },
  watch: {
    addPoint(data) {
      this.onAdd('click', data)
      this.$emit('on-change-point', this.listObject.list, 'red', this.count)
    },
    'editForm.taskName'(value) {
      this.errorTaskName = !value
    },
    isAdd(value) {
      console.log('value:' + value)
      this.isAddStatus = value
      //详情的情况
      if (value) {
        //新增
        this.listObject.columns = this.columns1
      } else {
        //详情
        this.listObject.columns = this.columns2
      }
    }
  },
  methods: {
    moment,
    getData(id) {
      this.taskId = id
      this.getDetail()
    },
    //关闭，缩进
    close() {
      this.loading = false
      this.$emit('close')
    },
    //取消，回到任务列表
    cancel() {
      this.loading = false
      // this.listObject.list = []
      // this.editForm = {}
      // this.errorTaskName = false
      this.$emit('cancel')
    },
    onAdd(type, data) {
      this.count += 1
      const newData = {
        editable: true,
        type: type,
        key: this.count,
        longitude: (data && data.longitude) || '',
        latitude: (data && data.latitude) || '',
        beginTime: '',
        endTime: ''
      }
      this.listObject.list = [...this.listObject.list, newData]
      this.cacheData = this.listObject.list.map(item => ({ ...item }))
    },
    onDetail() {
      if (this.listObject.list.length > 0) {
        let list = this.listObject.list
          .map(item => {
            if (!item.editable) {
              return item
            }
          })
          .filter(obj => obj !== undefined)
        if (this.listObject.list.length === list.length) {
          let arr = [{ list: list }]
          this.$emit('on-task-details-drawer', arr)
        } else {
          this.$message.error('请先操作完轨迹点信息')
        }
      } else {
        this.$message.error('还未创建轨迹点')
      }
    },
    onDelete(key) {
      const dataSource = [...this.listObject.list]
      this.listObject.list = dataSource.filter(item => item.key !== key)
      this.$emit('on-change-point', this.listObject.list, 'red', key)
    },
    onEdit(key) {
      const newData = [...this.listObject.list]
      const target = newData.filter(item => key === item.key)[0]
      if (target) {
        target.editable = true
        this.listObject.list = newData
      }
    },
    onSave(key) {
      let _this = this
      const newData = [...this.listObject.list]
      const target = newData.filter(item => key === item.key)[0]
      console.log(target)
      if (target) {
        if (!target.beginTime) {
          return this.$message.warning('开始时间不能为空')
        }
        if (!target.endTime) {
          return this.$message.warning('结束时间不能为空')
        }
        if (this.millionSecondToHour(target.endTime, target.beginTime) > 1) {
          this.$confirm({
            title: `当前添加数据时间前后时间差大于一小时，可能会导致数据量过于庞大，确定保存？`,
            // content: '你确定要删除这项告警配置吗？',
            okText: '确定',
            cancelText: '取消',
            onOk() {
              delete target.editable
              _this.listObject.list = newData
              _this.cacheData = newData.map(item => ({ ...item }))
            },
            onCancel() {}
          })
        } else {
          delete target.editable
          _this.listObject.list = newData
          _this.cacheData = newData.map(item => ({ ...item }))
        }
      }
      // 比较开始结束时间排序
      // this.sortList()
      this.$emit('on-change-point', this.listObject.list, 'red', key)
    },
    getDetail(datas) {
      this.listObject.list = datas
      this.count = datas.length - 1
      let arr = [
        {
          list: this.listObject.list
        }
      ]
      // 绘制轨迹
      this.$emit('on-task-details-drawer', arr)
    },
    onCopy(key) {
      const target = this.listObject.list.filter(item => key === item.key)[0]
      this.onAdd('click', target)
      this.$emit('on-change-point', this.listObject.list, 'red', this.count)
    },
    onCancel(key) {
      const newData = [...this.listObject.list]
      const target = newData.filter(item => key === item.key)[0]
      if (target) {
        Object.assign(target, this.cacheData.filter(item => key === item.key)[0])
        target.editable = false
        this.listObject.list = newData
      }
    },
    sortList() {
      const newData = [...this.listObject.list]
      let partList = newData.filter(item => {
        if (item.beginTime && item.endTime) {
          return item
        }
      })
      partList.sort((a, b) => {
        console.log(a, b)
        console.log(new Date(a.beginTime), new Date(b.beginTime))
        if (+new Date(a.beginTime) - +new Date(b.beginTime) === 0) {
          return +new Date(a.endTime) - +new Date(b.endTime)
        } else {
          return +new Date(a.beginTime) - +new Date(b.beginTime)
        }
      })
      this.listObject.list = [...new Set([...partList, ...newData])]
    },
    changeRange(date, dateString, key) {
      this.handleChange(dateString[0], key, 'beginTime')
      this.handleChange(dateString[1], key, 'endTime')
      // this.handleChange(convertDateFromString(dateString[0], 'yyyy-MM-dd'), key, 'beginTime')
      // this.handleChange(convertDateFromString(dateString[1], 'yyyy-MM-dd'), key, 'endTime')
    },
    handleChange(value, key, column) {
      console.log('value')
      console.log(value)
      const newData = [...this.listObject.list]
      const target = newData.filter(item => key === item.key)[0]
      if (target) {
        // 经纬度输入收尾去空格
        if (typeof value === 'string') {
          value = trim(value)
        }
        target[column] = value
        this.listObject.list = newData
      }
    },
    setTaskName() {
      this.editForm.taskName = trim(this.editForm.taskName)
    },
    onSubmit() {
      // 先进行时间排序
      // this.sortList()
      // this.editForm.incidentTaskId = this.$route.query.taskId
      // if (!this.editForm.taskName) {
      //   this.errorTaskName = true
      //   this.$message.error('任务名称未填写！')
      // } else
      console.log(this.listObject.list)
      if (this.isAccord(this.listObject.list)) {
        this.$message.error(this.errorTxt)
      } else {
        let _this = this
        const newData = [...this.listObject.list]
        let partList = newData.filter(item => {
          if (item.beginTime && item.endTime) {
            return item
          }
        })
        let pass = true
        let passIndex = []
        partList.forEach((e, index) => {
          if (this.millionSecondToHour(e.endTime, e.beginTime) > 1) {
            pass = false
            passIndex.push(index + 1)
          }
        })
        if (!pass) {
          this.$confirm({
            title: `您添加的第${passIndex.join(',第')}数据前后时间差大于一小时，可能会导致数据量过于庞大，确定提交？`,
            // content: '你确定要删除这项告警配置吗？',
            okText: '确定',
            cancelText: '取消',
            onOk() {
              _this.sortList()
              _this.editForm.trackList = _this.listObject.list.map(({ longitude, latitude, beginTime, endTime }) => {
                return {
                  longitude: parseFloat(longitude),
                  latitude: parseFloat(latitude),
                  beginTime,
                  endTime
                }
              })
              console.log(_this.editForm)
              _this.$emit('on-submit-success', _this.editForm.trackList)
              // _this.loading = true
            },
            onCancel() {}
          })
        } else {
          this.sortList()
          this.editForm.trackList = this.listObject.list.map(({ longitude, latitude, beginTime, endTime }) => {
            return {
              longitude: parseFloat(longitude),
              latitude: parseFloat(latitude),
              beginTime,
              endTime
            }
          })
          console.log(this.editForm)
          this.$emit('on-submit-success', this.editForm.trackList)
          // this.loading = true
        }
      }
    },
    millionSecondToHour(endTime, startTime) {
      let millionSecond = endTime - startTime
      return millionSecond / (1000 * 60 * 60)
    },
    isAccord(list) {
      let flag = false
      this.errorTxt = '第'
      list.forEach((item, index) => {
        if (testFloat(item.longitude) || testFloat(item.latitude) || !item.beginTime || !item.endTime) {
          this.errorTxt += `${index + 1}、`
          flag = true
          item.editable = true
        } else {
          item.editable = false
        }
      })
      this.errorTxt = this.errorTxt.replace(/、$/, '')
      this.errorTxt += '条输入不符合！'
      this.$forceUpdate()
      return flag
    }
  }
}
</script>

<style lang="less" scoped>
.track_drawer {
  /deep/.ant-drawer-content-wrapper {
    // background: rgba(0, 0, 0, 0.4);
    position: absolute;
    top: 0;
    bottom: 0;
    height: auto;
  }
  // .ant-drawer-content {
  // background: rgba(0, 0, 0, 0.4);
  // }
  /deep/.ant-drawer-header {
    // background: rgba(0, 0, 0, 0.4);
    border: none;
    // .ant-drawer-title {
    // color: #fff;
    // }
  }
  /deep/.ant-drawer-body {
    padding: 20px 0 44px 0;
    .add-box {
      padding: 0px 20px 24px;
      button {
        // background: rgba(24, 76, 151, 1);
        // border: rgba(24, 76, 151, 1);
        height: 40px;
      }
      .search {
        width: 200px;
        height: 40px;
        float: right;
        .ant-input-suffix {
          display: inline-block;
          width: 40px;
          height: 40px;
          // background: rgba(24, 76, 151, 1);
          right: 0;
          border-radius: 0 3px 3px 0;
          i {
            font-size: 20px;
            color: #fff;
            margin-left: 50%;
            margin-top: 50%;
            transform: translate(-50%, -50%);
          }
        }
      }
    }
  }

  .sk-add-table {
    /deep/.ant-table-thead > tr > th,
    /deep/.ant-table-tbody > tr > td {
      padding: 15px 4px;
    }
  }
  .ctr {
    display: flex;
    background-color: transparent;
    // color: #fff;
    padding: 20px 8px;
    input {
      width: 250px;
    }
    // button {
    // line-height: 40px;
    // background-color: rgba(24, 76, 151, 1);
    // border-color: rgba(24, 76, 151, 1);
    // margin-left: 50px;
    // }
  }
  .sk-add-table {
    input {
      background: transparent;
      // color: #fff;
    }
    // span {
    // color: #fff;
    // }
    // .editable-row-operations {
    // a {
    // color: #fff;
    // }
    // }
    /deep/.ant-calendar-picker-input {
      background: transparent;
    }
  }
}
</style>
